<template>
  <div>
    <h2>欢迎访问蜗牛养老后台管理系统</h2>
    <el-card>
      <!--搜索框11-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入食物名称" clearable v-model="name" @clear="search">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openAddFood">添加食材</el-button>
        </el-col>
      </el-row>
      <!--添加食材-->
      <el-dialog title="创建食材" :visible.sync="addFoodFormVisible" @close="closeAddFoodForm"
                 :close-on-click-modal="false">
        <el-form ref="addFoodForm" :rules="addFoodFormRules" :model="addFoodForm" label-width="150px" size="mini">
          <el-form-item label="食材名称" prop="foodname">
            <el-input v-model="addFoodForm.foodname"></el-input>
          </el-form-item>

          <el-form-item label="价格" prop="foodprice">
            <el-input v-model="addFoodForm.foodprice"></el-input>
          </el-form-item>

          <el-form-item label="食材照片">
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccessadd"
                :before-upload="beforeAvatarUpload"
                name="uploadImg"
                :headers="myHeader">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注" prop="foodremark">
            <el-input v-model="addFoodForm.foodremark"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddFoodForm">取 消</el-button>
          <el-button type="primary" @click="AddFoodFormOK">确 定</el-button>
        </div>
      </el-dialog>
      <!--主体数据-->
      <template>
        <el-table
            :data="foodList"
            style="width: 100%"
            :row-class-name="tableRowClassName"
        >
          <el-table-column
              label="编号"
              type="index"
             align="center">
          </el-table-column>
          <el-table-column
              label="图片"
              align="center">
            <template slot-scope="b">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="'http://localhost:10001/'+b.row.foodimg"
                  fit="cover"></el-image>
            </template>
          </el-table-column>
          <el-table-column
              prop="foodname"
              label="名称"
              align="center">
          </el-table-column>
          <el-table-column
              prop="foodprice"
              label="价格"
              align="center">
            <template slot-scope="scope">
              <span style="color: green">￥{{ scope.row.foodprice }}</span>
            </template>
          </el-table-column>
          <el-table-column
              label="状态"
              align="center"
          >
            <template slot-scope="scope">
              <span style="color: green" v-if="scope.row.foodstatus == 1">上架</span>
              <span style="color: red" v-if="scope.row.foodstatus == 0">下架</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="foodremark"
              label="备注"
              align="center">
          </el-table-column>

          <el-table-column label="操作"  align="center">
            <template v-slot="scope">
              <el-button
                  size="mini"
                  @click="handleEdit(scope.row.id)">编辑
              </el-button>
              <el-button
                  size="mini"
                  v-if="scope.row.foodstatus == 0"
                  type="success"
                  @click="handleEditStatus1(scope.row.id,1)">上架
              </el-button>
              <el-button
                  size="mini"
                  v-if="scope.row.foodstatus == 1"
                  type="warning"
                  @click="handleEditStatus2(scope.row.id,0)">下架
              </el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!--分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3, 6 , 12, 24]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

      <!--修改食材-->
      <el-dialog title="修改食材" :visible.sync="modifyFoodFormVisible" @close="closeModifyFoodForm"
                 :close-on-click-modal="false">
        <el-form ref="modifyFoodForm" :rules="modifyFoodFormRules" :model="modifyFoodForm" label-width="150px"
                 size="mini">
          <el-form-item label="食材名称" prop="foodname">
            <el-input v-model="modifyFoodForm.foodname"></el-input>
          </el-form-item>

          <el-form-item label="价格 / 元" prop="foodprice">
            <el-input v-model="modifyFoodForm.foodprice"></el-input>
          </el-form-item>
          <el-form-item label="高光瞬间">
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccessModify"
                :before-upload="beforeAvatarUpload"
                name="uploadImg"
                :headers="myHeader">
              <img v-if="imageUrlModify" :src="imageUrlModify" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注" prop="foodremark">
            <el-input v-model="modifyFoodForm.foodremark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeModifyFoodForm">取 消</el-button>
          <el-button type="primary" @click="modifyFoodFormOk">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {toRefs} from "vue";
import * as http from "http";

export default {
  data() {
    return {
      imageUrlModify: '',
      myHeader: {
        token: ''
      },
      imageUrl: '',
      olderName: '',
      olderList: [],
      uploadUrl: 'http://localhost:8088/upload/uploadImg',
      innerVisible: false,
      addFoodForm: {},
      modifyFoodForm: {},
      foodList: [],
      modifyFoodFormVisible: false,
      goBackOutFormVisible: false,
      addFoodFormVisible: false,
      name: '',
      pageNum: 1,
      olderPageNum: 1,
      pageSize: 3,
      olderPageSize: 3,
      total: 0,
      olderTotal: 0,
      addFoodFormRules: {
        foodname: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        foodprice: [
          {required: true, message: '不能为空', trigger: 'blur'},
          {pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '必须为大于0的数字', trigger: 'blur'}
        ],

      },
      modifyFoodFormRules: {
        foodname: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        foodprice: [
          {required: true, message: '不能为空', trigger: 'blur'},
          {pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '必须为大于0的数字', trigger: 'blur'}
        ],
      },
    };
  },
  methods: {
    tableRowClassName({rowIndex}) {
      if (rowIndex === 0) {
        return 'white-row'; // 第一行为白色
      } else if (rowIndex % 4 === 1) {
        return 'warning-row'; // 第二行和每隔三行后的行为绿色
      } else if (rowIndex % 2 === 0) {
        return ''; // 第二行和每隔三行后的行为绿色
      } else if (rowIndex % 3 === 2) {
        return 'white-row'; // 第三行和每隔三行后的行为白色
      } else {
        return 'success-row'; // 每隔三行后的行为黄色
      }
    },
    handleEditStatus1(id, status) {
      this.$confirm("你确定要上架吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let url = '/food/modifyFoodStatus/' + id + '/' + status;
        this.$axios.put(url).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success',
              duration: 1000
            });
            this.initFoodList();
          }else {
            this.$message({
              message: res.data.msg,
              type: 'error',
              duration: 1000
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "取消成功"
        })
      })
    },
    handleEditStatus2(id, status) {
      this.$confirm("你确定要下架吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let url = '/food/modifyFoodStatus/' + id + '/' + status;
        this.$axios.put(url).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success',
              duration: 1000
            });
            this.initFoodList();
          }else {
            this.$message({
              message: res.data.msg,
              type: 'error',
              duration: 1000
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "取消成功"
        })
      })
    },
    initHeaders() {
      let token = sessionStorage.getItem("token");
      this.myHeader.token = token;
    },
    handleDelete(id) {
      this.$confirm("你确定要删除此食材吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let url = '/food/deleteFood/' + id;
        this.$axios.delete(url).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success',
              duration: 1000
            });
            this.initFoodList();
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error',
              duration: 1000
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "取消成功"
        })
      })

    },
    openAddFood() {
      this.addFoodFormVisible = true;
      this.addFoodForm = {};
    },
    closeAddFoodForm() {
      this.addFoodFormVisible = false;
    },
    //选择长者
    selectOlder(id, name) {

      this.modifyLifeForm.olderId = id;

      this.modifyLifeForm.older.name = name;

      this.innerVisible = false;
    },
    selectOlderAdd(id, name) {

      this.addLifeForm.olderId = id;

      this.addLifeForm.name = name;

      this.innerVisible = false;
    },
    //文件上传之后
    handleAvatarSuccessadd(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.addFoodForm.foodimg = res.data;
    },
    //修改文件上传之后
    handleAvatarSuccessModify(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrlModify = "http://localhost:10001/" + res.data;
      this.modifyFoodForm.foodimg = res.data;
    },
    //文件上传之前
    beforeAvatarUpload(file) {
      //const isJPG = file.type === 'image/jpeg';
      const isLt20M = file.size / 1024 / 1024 < 20;

      /*if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }*/
      if (!isLt20M) {
        this.$message.error('上传头像图片大小不能超过 20MB!');
      }
      return isLt20M;
      // return isJPG && isLt2M;
    },
    //修改申请表
    handleEdit(id) {
      this.modifyFoodFormVisible = true;
      let url = "/food/selectFoodById/" + id;
      this.$axios.get(url).then((res) => {
        if (res.data.code == 200) {
          this.modifyFoodForm = res.data.data;
          this.imageUrlModify = "http://localhost:10001/" + res.data.data.foodimg;
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error',
            duration: 1000
          });
        }
      })
    },
    //确认添加
    AddFoodFormOK() {
      this.$refs.addFoodForm.validate((vaild) => {
        if (!vaild) {
          return
        } else {
          this.$confirm("你确定要添加吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            let url = '/food/addFood'
            this.$axios.post(url, this.addFoodForm).then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                  duration: 1000
                });
                this.initFoodList();
                this.addFoodFormVisible = false;
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error',
                  duration: 1000
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: "info",
              message: "取消成功"
            })
          })
        }
      })
    },
    //确认修改
    modifyFoodFormOk() {
      this.$refs.modifyFoodForm.validate((vaild) => {
        if (!vaild) {
          return
        } else {
          this.$confirm("你确定要修改吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            let url = '/food/modifyFood'
            this.$axios.put(url, this.modifyFoodForm).then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  message: res.data.msg,
                  type: 'success',
                  duration: 1000
                });
                this.initFoodList();
                this.modifyFoodFormVisible = false;
              } else {
                this.$message({
                  message: res.data.msg,
                  type: 'error',
                  duration: 1000
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: "info",
              message: "取消成功"
            })
          })
        }
      })
    },

    //关闭修改对话框
    closeModifyFoodForm() {
      this.modifyFoodFormVisible = false;
    },
    //查询长者
    search() {
      this.pageNum = 1;
      this.initLifeList();
    },
    //长者内置搜收框
    searchOlder() {
      this.olderPageNum = 1;
      this.initOlderList();
    },
    //初始化长者信息
    initOlderList() {
      let url = "/Older/list"
      this.$axios.get(url, {
        params: {
          name: this.olderName,
          now: this.olderPageNum,
          size: this.olderPageSize
        }
      }).then((res) => {
        if (res.data.code == 200) {
          this.olderList = res.data.data.list;
          this.olderPageNum = res.data.data.pageNum;
          this.olderPageSize = res.data.data.pageSize;
          this.olderTotal = res.data.data.total;
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error',
            duration: 1000
          });
        }
      })
    },
    //初始化查询生活数据
    initFoodList() {
      let url = "/food/list"
      this.$axios.get(url, {
        params: {
          name: this.name,
          now: this.pageNum,
          size: this.pageSize
        }
      }).then((res) => {
        if (res.data.code == 200) {
          this.foodList = res.data.data.list;
          this.pageNum = res.data.data.pageNum;
          this.pageSize = res.data.data.pageSize;
          this.total = res.data.data.total;
        } else {
          this.$message({
            message: res.data.msg,
            type: 'error',
            duration: 1000
          });
        }
      })
    },
    //改变条数查询
    handleSizeChange(size) {
      this.pageSize = size;
      this.pageNum = 1;
      this.initFoodList();
    },
    //改变页数查询
    handleCurrentChange(now) {
      this.pageNum = now;
      this.initFoodList();
    },
  },
  created() {
    this.initFoodList();
    this.initOlderList();
    this.initHeaders();
  }
}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>